﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetWing.Common;
using Senparc.Weixin;
using Senparc.Weixin.Exceptions;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using Senparc.Weixin.MP.CommonAPIs;

namespace NetWing.BPM.Admin.weixin
{
    public partial class auth2page : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            string appid = NetWing.Common.ConfigHelper.GetValue("AppID");
            string appsecret = NetWing.Common.ConfigHelper.GetValue("AppSecret");
            string code = Request["code"];
            if (string.IsNullOrEmpty(code))
            {
                Response.Write("<center><h1>您拒绝了授权！</h1></center>");
                Response.End();
            }
            //通过，用code换取access_token
            var result = OAuthApi.GetAccessToken(appid, appsecret, code);
            if (result.errcode == ReturnCode.请求成功)//请求成功
            {
                string openid = result.openid;//得到openid
                //这里的cookies需要多少写多少
                CookieHelper.WriteCookie("openid", openid);
                CookieHelper.WriteCookie("useropenid", openid);
                //Senparc.Weixin.Open.OAuthAPIs.OAuthApi.GetUserInfo(result.access_token, openid);
                var u = OAuthApi.GetUserInfo(result.access_token, openid);              
                CookieHelper.WriteCookie("nickname", HttpUtility.UrlEncode(u.nickname));//中文cookies要编码
                CookieHelper.WriteCookie("headimgurl", u.headimgurl);//用户头像写入cookies
                Response.Redirect(CookieHelper.GetCookie("returnurl"));
                //Response.Write("<center><h1>错误：" + result.errmsg + "</h1></center>");
                //Response.End();
            }
            else//请求失败
            {
                //跳转url
                string url = "https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzIyMzYyMzAzMw==&scene=124#wechat_redirect";
                Response.Redirect(url);
            }

        }
    }
}